import 'dart:io';

import 'package:stacked/stacked.dart';
import 'package:video_player/video_player.dart';
import 'package:vista/shared/models/tutorial_video.dart';
import 'package:vista/shared/services/tutorial_video_service.dart';

/// 视频播放视图模型
/// 管理视频播放页面的数据和状态
class VideoPlayerViewModel extends BaseViewModel {
  final TutorialVideoService _tutorialVideoService;
  final String videoId;

  VideoPlayerViewModel(this._tutorialVideoService, this.videoId);

  TutorialVideo? _video;
  TutorialVideo? get video => _video;

  VideoPlayerController? _controller;
  VideoPlayerController? get controller => _controller;

  bool _isInitialized = false;
  bool get isInitialized => _isInitialized;

  bool _isDisposing = false;
  bool get isDisposing => _isDisposing;

  /// 初始化数据
  Future<void> initialize() async {
    setBusy(true);
    try {
      await _loadVideo();
      await _initializePlayer();
    } finally {
      setBusy(false);
    }
  }

  /// 加载视频数据
  Future<void> _loadVideo() async {
    _video = await _tutorialVideoService.getVideoById(videoId);
    notifyListeners();
  }

  /// 初始化视频播放器
  Future<void> _initializePlayer() async {
    if (_video == null) return;

    // 判断是本地文件路径还是asset路径
    if (_video!.videoPath.startsWith('/') ||
        _video!.videoPath.startsWith('file://')) {
      // 本地文件路径
      final filePath = _video!.videoPath.replaceFirst('file://', '');
      _controller = VideoPlayerController.file(File(filePath));
    } else {
      // asset路径
      _controller = VideoPlayerController.asset(_video!.videoPath);
    }

    await _controller!.initialize();
    _controller!.setLooping(true);
    _controller!.play();
    _isInitialized = true;
    notifyListeners();

    // 增加访问次数
    await _tutorialVideoService.incrementViewCount(videoId);
  }

  /// 切换播放/暂停
  void togglePlayPause() {
    if (_isDisposing || _controller == null || !_isInitialized) return;

    if (_controller!.value.isPlaying) {
      _controller!.pause();
    } else {
      _controller!.play();
    }
    notifyListeners();
  }

  /// 删除视频
  Future<void> deleteVideo() async {
    await _tutorialVideoService.deleteVideo(videoId);
  }

  /// 清理视频播放器（在返回前调用）
  Future<void> cleanup() async {
    if (_isDisposing) return;
    _isDisposing = true;
    if (_controller != null) {
      await _controller!.pause();
      await _controller!.dispose();
      _controller = null;
      _isInitialized = false;
    }
  }

  @override
  void dispose() {
    // 如果 controller 还未清理，则清理它
    if (!_isDisposing && _controller != null) {
      _isDisposing = true;
      _controller!.pause();
      _controller!.dispose();
      _controller = null;
      _isInitialized = false;
    } else {
      _isDisposing = true;
    }
    super.dispose();
  }
}
